package com.happybz.controller.interceptor;

import com.happybz.utils.JSONResult;
import com.happybz.utils.JsonUtils;
import com.happybz.utils.RedisOperator;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class UserTokenInterceptor implements HandlerInterceptor {

    /**
     * 不想这么写的时候，可以引入Lombok后，在类上使用@Slf4j，就能直接使用log.info等来操作了
     */
    Logger log = LoggerFactory.getLogger(UserTokenInterceptor.class);

    @Autowired
    private RedisOperator redisOperator;

    public static final String REDIS_USER_TOKEN = "redis_user_token";

    /**
     * 拦截请求，在访问controller调用之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        log.debug("进入到拦截器，被拦截,preHandle拦截的请求路径是{}",requestURI);
//
//        Map ParameterMap =  request.getParameterMap();
//        Map reqMap = new HashMap();
//        Set<Map.Entry<String,String[]>> entry = ParameterMap.entrySet();
//        Iterator<Map.Entry<String,String[]>> it = entry.iterator();
//        while (it.hasNext()){
//            Map.Entry<String,String[]>  me = it.next();
//            String key = me.getKey();
//            String value = me.getValue()[0];
//            reqMap.put(key,value);
//        }
//        String queryString = JsonUtils.objectToJson(reqMap);
//        log.info("queryString..." + queryString);

//        System.out.println("进入到拦截器，被拦截。。。");

        String userId = request.getHeader("headerUserId");
        String userToken = request.getHeader("headerUserToken");

        if (StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(userToken)) {
            String uniqueToken = redisOperator.get(REDIS_USER_TOKEN + ":" + userId);
            if (StringUtils.isBlank(uniqueToken)) {
                log.debug("请登录...");
                returnErrorResponse(response, JSONResult.errorMsg("请登录..."));
                return false;
            } else {
                if (!uniqueToken.equals(userToken)) {
                    log.debug("账号在异地登录...");
                    returnErrorResponse(response, JSONResult.errorMsg("账号在异地登录..."));
                    return false;
                }
            }
        } else {
            log.debug("请登录...");
            returnErrorResponse(response, JSONResult.errorMsg("请登录..."));
            return false;
        }


        /**
         * false: 请求被拦截，被驳回，验证出现问题
         * true: 请求在经过验证校验以后，是OK的，是可以放行的
         */
        return true;
    }

    public void returnErrorResponse(HttpServletResponse response,
                                    JSONResult result) {
        OutputStream out = null;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/json");
            out = response.getOutputStream();
            out.write(JsonUtils.objectToJson(result).getBytes("utf-8"));
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 请求访问controller之后，渲染视图之前
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle执行{}",modelAndView);
    }

    /**
     * 请求访问controller之后，渲染视图之后
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion执行异常{}",ex);
    }
}
